package com.wlyy.his.controller.common;

import com.wlyy.his.bean.common.dto.LoginDto;
import com.wlyy.his.common.api.CommonResult;
import com.wlyy.his.common.util.RedisUtil;
import com.wlyy.his.infrastructure.common.AuthCommon;
import com.wlyy.his.infrastructure.common.RequestUserInfo;
import com.wlyy.his.service.ums.IAccountService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;


/**
 * @author: 10097
 * @Date: 2021/8/26 13:52
 * @Description:
 */
@RestController
@RequestMapping("/token")
@Slf4j
public class TokenController {

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private IAccountService iAccountService;

    @RequestMapping("logon")
    public void login(HttpServletResponse response) {
        RequestUserInfo userInfo = new RequestUserInfo();
        userInfo.setAccountId("id_account_1123");
        userInfo.setAccount("zhangjiale1994");
        userInfo.setName("张家乐");
        userInfo.setIdPerson("id_person_1234");
        String token = UUID.randomUUID().toString();
        redisUtil.set(AuthCommon.CACHE_USER_REDIS_KEY + token, userInfo, AuthCommon.TOKEN_CACHE_TIME);
        Cookie cookie = new Cookie(AuthCommon.PRE_COOKIE_NAME, token);
        cookie.setMaxAge(AuthCommon.TOKEN_CACHE_TIME.intValue());
        response.addCookie(cookie);
    }


    /**
     * 登录接口
     * @param loginDto 对象
     * @return CommonResult 对象
     */
    @PostMapping("/login")
    public CommonResult login(@RequestBody LoginDto loginDto) {
        String token = iAccountService.login(loginDto);
        if (StringUtils.isNotBlank(token)){
            return CommonResult.success(token);
        }else {
            return CommonResult.failed();
        }
    }

}
